package com.dong.user.thrift;

import com.dong.thrift.message.MessageService;
import com.dong.thrift.user.UserService;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TFastFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ServiceProvider {
    @Value("${thrift.user.ip}")
    private String serverIp;
    @Value("${thrift.user.port}")
    private int serverPort;

    @Value("${thrift.message.ip}")
    private String messageServerIp;
    @Value("${thrift.message.port}")
    private int messageServerPort;

    private enum ServiceType{
        USER,
        MESSAGE
    }

    public UserService.Client getUserService() {
       return getService(serverIp,serverPort,ServiceType.USER);
    }

    public MessageService.Client getMessageService() {
      return getService(messageServerIp,messageServerPort,ServiceType.MESSAGE);
    }
    public <T> T getService(String ip,int port,ServiceType serviceType) {
        System.out.println("getService -> "+ip+"   -- "+port);
        TSocket socket = new TSocket(ip,port,3000);

        TTransport transport = new TFastFramedTransport(socket);

        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
            return null;
        }
        TBinaryProtocol protocol = new TBinaryProtocol(transport);
        TServiceClient result = null;
        System.out.println("getService -> "+ip+"   -- "+port);
        switch (serviceType) {
            case  USER: {
                result = new UserService.Client(protocol);
                break;
            }
            case MESSAGE: {
                result = new MessageService.Client(protocol);
                break;
            }
          }
        return (T)result;
    }
}
